import friendSqlite from "@/sqlite_services/friend.js";
import friendApi from "@/services/api/friends.js"
export default {
    state: {
		friendList:[],//好友列表
        friendInfo:{},//当前查看的好友信息
		friendOnline:{},//在线好友
		onlineTimer:null,//获取在线好友的计时器,30秒获取一次吧
		mykefu:null,//我的所属客服
    },
    mutations: {
        setFriendInfo(state, data) {
			state.friendInfo = data
        },
		//更新内容
		updateFriendInfo(state, data) {
			// 判断ID是否相同
			if (state.friendInfo.user_id == data.user_id) {
				for (let key in data) {
					if (data[key] != state.friendInfo[key]) {
						Vue.set(state.friendInfo, key, data[key]);
					}
				}
			}
		},
		
		
		//好友列表
		setFriendList(state, data) {
			state.friendList = data
		},
		// 更新 friendList 中的特定元素
		updateFriendListById(state, { friend_idx, data }) {
			const index = state.friendList.findIndex(friend => friend.friend_idx == friend_idx);
			if (index !== -1) {
				//有变化再更新，没变化就不更新了避免页面重新渲染
				for (let key in data) {
					if (data[key] != state.friendList[index][key]) {
						Vue.set(state.friendList[index], key, data[key]);
					}
				}
			}
			
		},
		//删除了分组更新group_Id
		updateFriendListGroupByid(state, group_id){
			state.friendList.map(item=>{
				if(item.friend_group == group_id){
					item.friend_group = 0
				}
			})
		},
		// 添加一个新的friend
		addFriendList(state, data) {
			// 检查是否已经存在相同的 friend_idx
			const existingFriend = state.friendList.find(friend => friend.friend_idx == data.friend_idx);
			
			if (!existingFriend) {
				state.friendList.push(data);
			}
		},
		// 删除一个friend
		deleteFriendListById(state, friend_idx) {
			const index = state.friendList.findIndex(friend => friend.friend_idx == friend_idx);
			if (index !== -1) {
				state.friendList.splice(index, 1);
			}
		},
		//设置在线好友
		SET_FRIEND_ONLINE(state, onlineFriends) {
			state.friendOnline = onlineFriends;
		},
		//设置在线好友计时器
		SET_ONLINE_TIMER(state, timer) {
			state.onlineTimer = timer;
		},
		//关闭在线好友计时器
		CLEAR_ONLINE_TIMER(state) {
			if (state.onlineTimer) {
				clearInterval(state.onlineTimer);
				state.onlineTimer = null;
			}
		},
		//设置我的客服
		SET_MY_KEFU(state,data) {
			state.mykefu = data
		},
    },
    actions: {
		async anewGetFriend({ state,commit,dispatch,getters }){
			try {
				let res = await friendApi.friendList()
				if (res) {
					dispatch('setFriendList', res.list)
				}
			} catch (e) {
				console.log(e);
			}
			//好友数量
			try {
				let applyres = await uni.$api.friends.applyList({
					page: 1,
					limit: 1
				})
				if(applyres && applyres.code == 200){
					 dispatch('updateFriendBadge',{ type: 'set', count:applyres.data.total})
				}
			} catch (e) {
				console.log(e);
			}
		},
		//设置friendList
		async setFriendList({ state,commit,dispatch,getters }, data) {
			console.log(data);
			commit('setFriendList', data);
			
			const friendList = [];
			const userInfoList = [];
			
			data.forEach(item => {
			    friendList.push({
			        friend_idx: item.friend_idx,
			        friend_group: item.friend_group || 0,
			        create_time: item.friend_create_time || 0,
			        update_time: item.friend_update_time || 0
			    });
			
			    userInfoList.push({
			        user_id: item.friend_idx,
			        nick_name: item.nick_name,
			        avatar_url: item.avatar_url,
			        friend_remark: item.friend_remark || ''
			    });
			});
			//添加或替换
			friendSqlite.batchAddOrEditFrindList(friendList,'friend_idx')
			//添加或修改用户
			friendSqlite.batchAddOrEditUserInfo(userInfoList,'user_id')
		},
		//添加friendList
		async addFriendList({ commit,dispatch,getters }, data) {
			
			commit('addFriendList', data);
			
			friendSqlite.addOrEditFrindList({
				friend_idx: item.friend_idx,
				create_time: item.create_time || 0
			})
			friendSqlite.addOrEditUserInfo({
				user_id: item.friend_idx,
				nick_name: item.nick_name,
				avatar_url: item.avatar_url,
				friend_remark:item.friend_remark || '',
			})
		},
		//更新friendList
		async updateFriendList({ commit }, { friend_idx, data }) {
			commit('updateFriendListById', { friend_idx, data });
			//不需要更新数据库，因为数据库啥也没有就存个时间和id 能用的到 再弄把
			//如果分组存在
			if(data.friend_group){
				await friendSqlite.editFrindList(friend_idx,{
					friend_group:data.friend_group
				})
			}
		},
		//删除了分组更新分组
		async updateFriendListGroup({ commit }, group_id) {
			commit('updateFriendListGroupByid', group_id);
			//不需要更新数据库，因为数据库啥也没有就存个时间和id 能用的到 再弄把
			await friendSqlite.editFrindListGroup(group_id)
			
			//userinfo表里的也需要清掉
			friendSqlite.editUserInfoCustom({ field: 'friend_group_id', val: `'${group_id}'`},{
				friend_group_id: 0,
				friend_group_name: ''
			})
		},
		
		//删除friendList
		async delFriendList({ commit,dispatch,getters }, friend_idx) {
			commit('deleteFriendListById', friend_idx);
			await friendSqlite.delFrindList(friend_idx)
		},
		//获取在线好友
		async getOnlineFriend({ commit }) {
			try {
				let resList = await friendApi.onlineFriend();
				if(resList){
					let onlineFriends = resList.reduce((acc, id) => {
						acc[id] = true;
						return acc;
					}, {});
					commit('SET_FRIEND_ONLINE', onlineFriends);
				}else{
					commit('SET_FRIEND_ONLINE', {});
				}
			} catch (error) {
				console.error('获取在线好友失败:', error);
			}
		},
		//开始获取在线好友
		startOnlineFriendTimer({ dispatch, commit, state }) {
			dispatch('stopOnlineFriendTimer')//每次开始前清除一下
			dispatch('getOnlineFriend'); // 立即获取一次在线好友
			let timer = setInterval(() => {
				dispatch('getOnlineFriend');
			}, 30000); // 每30秒获取一次
			commit('SET_ONLINE_TIMER', timer);
		},
		//关闭在线好友计时器
		stopOnlineFriendTimer({ commit }) {
			commit('CLEAR_ONLINE_TIMER');
			commit('SET_FRIEND_ONLINE', {});
		},
		//获取我的客服
		async getMyKefu({ dispatch, commit, state }){
			try{
				let kefuRes = await uni.$api.friends.getCustomerInfo()
				if(kefuRes && kefuRes.code == 200){
					commit('SET_MY_KEFU',kefuRes.data);
				}
			}catch(e){
				//TODO handle the exception
			}
		}
    }
};